package org.quartz.utils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class PoolingConnectionProvider implements ConnectionProvider {

    public static final String DB_DRIVER = "driver";

    public static final String DB_URL = "URL";

    public static final String DB_USER = "user";

    public static final String DB_PASSWORD = "password";

    public static final String DB_MAX_CONNECTIONS = "maxConnections";

    public static final String DB_VALIDATION_QUERY = "validationQuery";
    
    public static final int DEFAULT_DB_MAX_CONNECTIONS = 10; 

    private BasicDataSource datasource;

    public PoolingConnectionProvider(String dbDriver, String dbURL,
            String dbUser, String dbPassword, int maxConnections,
            String dbValidationQuery) throws SQLException {
        initialize(
            dbDriver, dbURL, dbUser, dbPassword, 
            maxConnections, dbValidationQuery);
    }

    public PoolingConnectionProvider(Properties config) throws SQLException {
        PropertiesParser cfg = new PropertiesParser(config);
        initialize(
            cfg.getStringProperty(DB_DRIVER), 
            cfg.getStringProperty(DB_URL), 
            cfg.getStringProperty(DB_USER, ""), 
            cfg.getStringProperty(DB_PASSWORD, ""), 
            cfg.getIntProperty(DB_MAX_CONNECTIONS, DEFAULT_DB_MAX_CONNECTIONS), 
            cfg.getStringProperty(DB_VALIDATION_QUERY));
    }
    
    private void initialize(
        String dbDriver, 
        String dbURL, 
        String dbUser,
        String dbPassword, 
        int maxConnections, 
        String dbValidationQuery) throws SQLException {
        if (dbURL == null) {
            throw new SQLException(
                "DBPool could not be created: DB URL cannot be null");
        }
        
        if (dbDriver == null) {
            throw new SQLException(
                "DBPool '" + dbURL + "' could not be created: " +
                "DB driver class name cannot be null!");
        }
        
        if (maxConnections < 0) {
            throw new SQLException(
                "DBPool '" + dbURL + "' could not be created: " + 
                "Max connections must be greater than zero!");
        }

        datasource = new BasicDataSource();
        datasource.setDriverClassName(dbDriver);
        datasource.setUrl(dbURL);
        datasource.setUsername(dbUser);
        datasource.setPassword(dbPassword);
        datasource.setMaxActive(maxConnections);
        if (dbValidationQuery != null) {
            datasource.setValidationQuery(dbValidationQuery);
        }
    }
    
    protected BasicDataSource getDataSource() {
        return datasource;
    }

    public Connection getConnection() throws SQLException {
        return datasource.getConnection();
    }
    
    public void shutdown() throws SQLException {
        datasource.close();
    }    
}
